package com.dragon.wangyiwork.service.impl;

import com.dragon.wangyiwork.entity.Commodity;
import com.dragon.wangyiwork.repository.CommodityRepository;
import com.dragon.wangyiwork.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    private CommodityRepository commodityRepository;


    @Override
    public List<Commodity> getAllCommodity() {
        return commodityRepository.findAll();
    }

    @Override
    public List<Commodity> getNotBuyCommodity() {
        List<Commodity> commodities = commodityRepository.findCommoditiesByHasBuy(0);
        commodities.addAll(commodityRepository.findCommoditiesByHasBuy(2));
        return commodities;
    }

    @Override
    public Commodity getCommodityById(Integer id) {
        return commodityRepository.findById(id).orElse(null);
    }

    @Override
    public Commodity publicCommodity(Commodity commodity) {
        return commodityRepository.saveAndFlush(commodity);

    }

    @Override
    public List<Commodity> getAccount() {
        return commodityRepository.findCommoditiesByHasBuy(1);
    }

    @Override
    public List<Commodity> getSettleAccount() {
        return commodityRepository.findCommoditiesByHasBuy(2);
    }

    @Override
    @Transactional
    public Commodity addCart(Commodity commodity) {
        Commodity commodity1 = commodityRepository.findById(commodity.getId()).orElse(null);
        commodityRepository.updateCommodityHasBuyToCart(2,commodity.getCount()+commodity1.getCartCount(),commodity.getId());
        return commodityRepository.findById(commodity.getId()).orElse(null);
    }

    @Override
    @Transactional
    public void buyCommodity(Commodity[] commodityList) {
        for (int i = 0; i < commodityList.length; i++) {
            Commodity commodity = commodityList[i];
            commodityRepository.updateCommodityBuy(1,commodity.getPrice(),commodity.getCount(),new Date(),commodity.getId());
        }
    }

    @Transactional
    @Override
    public Commodity updateCommodity(Commodity commodity) {
        commodityRepository.updateCommodityPublic(commodity.getTitle(),commodity.getSummary(),commodity.getPic(),commodity.getText(),commodity.getPrice(),commodity.getId());
        Optional<Commodity> commodity1 = commodityRepository.findById(commodity.getId());
        return commodity1.orElse(null);
    }

    @Override
    @Transactional
    public void deleteCommodityById(Integer id) {
        commodityRepository.deleteById(id);
    }

}
